package Algorithms.BinarySearchWithoutRecursion_01;

/*
 * @Author 罗
 * @date 2020/3/28 - 9:43 下午
 *
 */

public class BinarySearch {
    /**
     * 非递归的实现二分查找算法
     * @param array
     * @param findValue
     * @return
     */
    public static int binarySearch(int[] array, int findValue) {
        int left = 0;
        int right = array.length - 1;
        int midIndex;
        while (left <= right) {

            midIndex = (left + right) / 2;

            if (array[midIndex] > findValue) {
                right = midIndex - 1;
            } else if (array[midIndex] < findValue) {
                left = midIndex + 1;
            } else if (array[midIndex] == findValue) {
                return midIndex;
            }
        }

        return -1;
    }
}
